package cc.zy.base.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.qrcode.EncodeHintType;
import com.itextpdf.text.pdf.qrcode.ErrorCorrectionLevel;

/**
 * 导出pdf
 *
 * @author wanglei
 *
 */
public class CreatePdfUtil {
    //private static Logger logger = LoggerFactory.getLogger(CreatePdfUtil.class);
    // 字体
    public static final String FONT_STZHONGS = "pdf_mould/font/STZHONGS.TTF";

    // /**
    // * 创建pdf
    // * @param t ftl模板
    // * @param mp 数据
    // * @param filePath 文件路径
    // * @param fileName html文件名称
    // * @param outFileNameWsy 无水印文件名�?
    // * @param outFileName 有水印文件名�?
    // */
    // public static void CreatePdf(Template t, Map<String, Object> mp,
    // String filePath, String fileName, String outFileNameWsy,
    // String outFileName) {
    // // 生成html文件
    // File outFile = new File(filePath + "/" + fileName);
    // Writer out = null;
    // try {
    // out = new BufferedWriter(new OutputStreamWriter(
    // new FileOutputStream(outFile), "utf-8"));
    // } catch (FileNotFoundException e1) {
    // e1.printStackTrace();
    // } catch (UnsupportedEncodingException e) {
    // e.printStackTrace();
    // }
    //
    // try {
    // // 数据入模�?
    // t.process(mp, out);
    //
    // String filePdfName = filePath + "/" + outFileNameWsy;
    // // 输出完成，下载开�?
    // File file = new File(filePdfName);
    // if (file.exists()) {
    // file.createNewFile();
    // }
    // OutputStream os = new FileOutputStream(filePdfName);
    // ITextRenderer renderer = new ITextRenderer();
    // String url = new File(filePath + "/" + fileName).toURI().toURL()
    // .toString();
    // renderer.setDocument(url);
    // // 解决中文
    // ITextFontResolver fontResolver = renderer.getFontResolver();
    //
    // try {
    // fontResolver.addFont(
    // "com/koteladt/jzdy/util/expword/simsun.ttc",
    // BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    // fontResolver.addFont(
    // "com/koteladt/jzdy/util/expword/simhei.ttf",
    // BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    // fontResolver.addFont(
    // "com/koteladt/jzdy/util/expword/STZHONGS.TTF",
    // BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    // fontResolver.addFont(
    // "com/koteladt/jzdy/util/expword/fzcsjt.TTF",
    // BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    // } catch (DocumentException e) {
    // e.printStackTrace();
    // }
    // renderer.layout();
    // try {
    // renderer.createPDF(os);
    // } catch (DocumentException e) {
    // e.printStackTrace();
    // }
    // logger.info("html转换pdf完成");
    // renderer.finishPDF();
    // os.close();
    // os.flush();
    // out.close();
    // out.close();
    // // 加水�?
    // try {
    // WaterPrint.setWatermark(filePath + "/" + outFileName,
    // filePdfName, CreatePdfUtil.class.getClassLoader()
    // .getResource("").getPath());
    // } catch (DocumentException e) {
    // e.printStackTrace();
    // }
    // logger.info("pdf水印转换完成");
    // } catch (TemplateException e) {
    // e.printStackTrace();
    // } catch (IOException e) {
    // logger.error("文件生成失败");
    // }
    // }

    /**
     * 文件合并
     *
     * @param outPdfFile
     * @param mergeFiles
     * @param filePath
     */
    public static void MergeFiles(File outPdfFile, List<String> mergeFiles,
                                  String filePath, Rectangle rectangle) {
        try {
            FileOutputStream out = new FileOutputStream(outPdfFile);
            Document allDocument = new Document(rectangle);
            PdfWriter writer = PdfWriter.getInstance(allDocument, out);
            allDocument.open();
            PdfContentByte cb = writer.getDirectContent();
            java.util.List<PdfReader> readers = new ArrayList<PdfReader>();
            for (String fileName : mergeFiles) {
                PdfReader reader = new PdfReader(filePath + "/" + fileName);
                readers.add(reader);
                // reader.close();
            }

            int pageOfCurrentReaderPDF = 0;
            Iterator<PdfReader> iteratorPDFReader = readers.iterator();

            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();

                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                    allDocument.newPage();
                    pageOfCurrentReaderPDF++;
                    PdfImportedPage page = writer.getImportedPage(pdfReader,
                            pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);
                }
                pageOfCurrentReaderPDF = 0;
            }

            out.flush();
            allDocument.close();
            for (PdfReader pdfReader : readers) {
                pdfReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            //logger.error("pdf合并出错!!" + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * 处理为空方法
     * @param name
     * @param value
     * @param dataMap
     */
    public static void dealNan(String name, Integer value, Map dataMap) {
        if (value != null) {
            dataMap.put(name, value == 0 ? "" : value);
        } else {
            dataMap.put(name, "");
        }
    }

    /**
     * 设置pdf编码格式
     *
     * @return
     */
    public static Map<EncodeHintType, Object> setEncodePdf() {

        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        return hints;

    }

    /**
     * 数字为null和为零�?�为�?
     *
     * @param value
     * @return
     */
    public static String getValue(Object value) {
        if (value == null) {
            value = "";
        } else if (Double.valueOf(String.valueOf(value)) == 0) {
            value = "";
        }
        return value + "";
    }


    /**
     * 取得字体
     *
     * @param ps
     * @param map
     * @throws DocumentException
     * @throws IOException
     */
    public static BaseFont getBaseFont(String font) {
        BaseFont baseFont=null;
        try {
            baseFont = BaseFont.createFont(font,
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baseFont;

    }
    /**
     * 为调拨和调修服务
     *
     * @param ps
     * @param map
     * @throws DocumentException
     * @throws IOException
     */
    public static void fontBold(PdfStamper ps, Map<String, String> map,Map<String, Integer> alignMap)
            throws DocumentException, IOException {
        BaseFont baseFont = BaseFont.createFont(FONT_STZHONGS,
                BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font boldFont = new Font(baseFont, 9.1f, Font.NORMAL);
        AcroFields s = ps.getAcroFields();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            // 设置加粗只能用这种方�?
            List<AcroFields.FieldPosition> multiLinePosition = s
                    .getFieldPositions(entry.getKey());
            Rectangle rectangle = multiLinePosition.get(0).position;
            float left = rectangle.getLeft();
            float right = rectangle.getRight();
            float top = rectangle.getTop();
            float bottom = rectangle.getBottom();
            PdfContentByte pdfContentByte = ps.getOverContent(1);
            ColumnText columnText = new ColumnText(pdfContentByte);
            Rectangle r = new Rectangle(left, bottom, right, top);
            columnText.setSimpleColumn(r);
            // Chunk chunk = new Chunk(String.valueOf(entry.getValue()),

            // boldFont);
            Chunk chunk = new Chunk(String.valueOf(entry.getValue()), boldFont);

            Paragraph paragraph = new Paragraph(chunk);
            columnText.addText(paragraph);
            if(alignMap != null && alignMap.containsKey(entry.getKey())){
                paragraph.setAlignment(alignMap.get(entry.getKey()));
            }else{
                paragraph.setAlignment(Element.ALIGN_CENTER);
            }

            columnText.addElement(paragraph);
            columnText.go();
        }

    }
}
